<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>设置门店位置</title>
    <script src="https://webapi.amap.com/maps?v=2.0&key=11345392d271e3153762c18695234095"></script>
    <style>
        html, body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 80%;
            overflow: hidden;
        }

        #mapContainer {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }

        .map-title {
            position: absolute;
            top: 20px;
            left: 20px;
            z-index: 1000;
            background: rgba(255,255,255,0.8);
            padding: 10px 20px;
            border-radius: 4px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
            font-size: 18px;
        }

        .map-controls {
            position: absolute;
            bottom: 30px;
            right: 20px;
            z-index: 1000;
            display: flex;
            gap: 10px;
        }

        .map-controls button, .map-controls a {
            padding: 10px 20px;
            background: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.2);
            transition: background 0.3s;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .map-controls button:hover, .map-controls a:hover {
            background: #0b7dda;
        }

        #saveBtn {
            background: #4CAF50;
        }

        #saveBtn:hover {
            background: #45a049;
        }

        #repositionBtn {
            background: #FF9800;
        }

        #repositionBtn:hover {
            background: #F57C00;
        }

        #homeBtn {
            background: #9C27B0;
        }

        #homeBtn:hover {
            background: #7B1FA2;
        }
    </style>
</head>
<body>
<div th:insert="~{common/common::topbar}"></div>
<div class="map-title">
    选择门店位置
</div>

<div id="mapContainer"></div>

<!-- 控制按钮容器 -->
<div class="map-controls">
    <button id="repositionBtn">重新定位</button>
    <button id="saveBtn">保存位置</button>
    <a id="homeBtn" th:href="@{/chart/refresh}">回到首页</a>
</div>

<script>
    var map = new AMap.Map('mapContainer', {
        zoom: 15,
        resizeEnable: true
    });

    var marker = new AMap.Marker({
        map: map,
        draggable: true
    });

    // 定位功能实例
    var geolocation;

    // 初始化地图和定位功能
    function initMap() {
        // 加载Geolocation插件
        AMap.plugin('AMap.Geolocation', function() {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,   // 是否使用高精度定位
                timeout: 10000,            // 定位超时时间
                position: 'RB',           // 定位按钮位置
                offset: [10, 20],         // 定位按钮偏移量
                zoomToAccuracy: true      // 定位成功后调整地图视野
            });

            // 添加定位工具到地图
            map.addControl(geolocation);

            // 页面加载时自动定位
            locateUser();
        });
    }

    // 定位用户当前位置
    function locateUser() {
        geolocation.getCurrentPosition(function(status, result) {
            if (status === 'complete') {
                onLocationComplete(result);
            } else {
                console.error('定位失败:', result);
                alert('自动定位失败，请手动选择位置或点击重新定位按钮。错误信息：' + result.message);
                // 默认位置（北京）
                setMarkerPosition([116.397428, 39.90923]);
            }
        });
    }

    function onLocationComplete(result) {
        console.log('定位成功:', result);
        var lng = result.position.lng;
        var lat = result.position.lat;
        setMarkerPosition([lng, lat]);

        // 显示定位精度范围
        if(result.accuracy) {
            var circle = new AMap.Circle({
                center: [lng, lat],
                radius: result.accuracy,  // 精度半径
                strokeColor: "#0091EA",
                strokeOpacity: 0.5,
                strokeWeight: 1,
                fillColor: "#0091EA",
                fillOpacity: 0.2,
                zIndex: 10
            });
            circle.setMap(map);
        }
    }

    // 设置标记位置并居中地图
    function setMarkerPosition(position) {
        marker.setPosition(position);
        map.setCenter(position);
    }

    // 点击地图设置标记位置
    map.on('click', function (e) {
        setMarkerPosition(e.lnglat);
    });

    // 保存位置到后台
    function saveLocation() {
        var position = marker.getPosition();
        if (!position) {
            alert('请先选择位置');
            return;
        }

        fetch('/location/saveLocation', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                longitude: position.lng,
                latitude: position.lat
            })
        }).then(res => res.text())
            .then(data => alert("位置已保存" ))
            .catch(err => {
                console.error('保存位置失败:', err);
                alert('保存失败，请重试');
            });
    }

    // 按钮事件绑定
    document.getElementById('repositionBtn').addEventListener('click', function() {
        locateUser();
    });

    document.getElementById('saveBtn').addEventListener('click', function() {
        saveLocation();
    });

    // 初始化地图
    initMap();
</script>
</body>
</html>